package cn.bonoon.kernel.expression.resolver;

import cn.bonoon.kernel.expression.ExpressionParseContext;
import cn.bonoon.kernel.expression.ExpressionPropertyResolver;

public abstract class AbstractExpressionPropertyResolver implements ExpressionPropertyResolver{
	
	private final String command;
	private final int commandLength;
	
	protected AbstractExpressionPropertyResolver(String command){
		this.command = command;
		this.commandLength = command.length();
	}
	
	public static ExpressionPropertyResolver factory(){
		return new ExpressionPropertyResolver(){
			
			private ExpressionPropertyResolver[] resolvers = {
				new FieldExpressionResolver(),
				new ModelExpressionResolver(),
				new UserExpressionResolver(),
				new SesssionExpressionResolver()
			};
			
			@Override
			public boolean resolver(ExpressionParseContext context, String expression) throws Exception{
				for(ExpressionPropertyResolver resolver : resolvers){
					if(resolver.resolver(context, expression)){
						return true;
					}
				}
				return false;
			}
			
		};
	}
	
	@Override
	public boolean resolver(ExpressionParseContext context, String expression) throws Exception{
		if(expression.startsWith(command) && expression.charAt(commandLength) == ' '){
			return internalResolver(context, expression.split(" "));
		}
		return false;
	}
	
	/** 生成查询语句的表达式；如果子类需要处理特殊情况，则可以重写，如直接赋值等 */
	protected boolean internalResolver(ExpressionParseContext context, String[] commands)throws Exception{
		context.append('?');
		return true;
	}
}
